package com.wind.sqlite.tools;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ProcessUtil {


    public static void main(String[] args) {
//        String[] cmds={"echo","aaa"};//必须分开写，不能有空格
//        System.out.println(execCurl(cmds));

        List<String> commandList = new ArrayList<>();
        commandList.add("curl");

        commandList.add("--request");

        commandList.add("DELETE");

        commandList.add("'http://172.18.0.4:5555/se/grid/node/session/576aad0382946d0c907c077aa932afe0'");
        commandList.add("--header");

        commandList.add("'X-REGISTRATION-SECRET;'");

        String[] aaas = commandList.toArray(new String[commandList.size()]);

    }

    public static String execCurl(String[] cmds) {
        String cUrlToKeyCloak = "";
        for (String aaa : cmds) {
            cUrlToKeyCloak += aaa + " ";
        }
        System.out.println(cUrlToKeyCloak);
        String cKeyResponse = "";
        ProcessBuilder processBuilder = new ProcessBuilder();
        if (!System.getProperty("os.name").contains("Windows"))
            processBuilder.command("bash", "-c", cUrlToKeyCloak);
        else
            processBuilder.command("cmd.exe", "/c", cUrlToKeyCloak);

        try {
            Process process = processBuilder.start();
            StringBuilder output = new StringBuilder();

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }

            int exitVal = process.waitFor();
            if (exitVal == 0) {
                log.info("Curl command to keyCloak requested ...");
                log.info("cKey response = " + output);
                cKeyResponse = output.toString();
                return cKeyResponse;
            } else {
                log.error("Curl command to keyCloak executed with error ...");
                log.info("cKey response = " + output);
            }


        } catch (IOException e) {
            System.out.print("error");
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.print("error");
            e.printStackTrace();
        }
        return null;

    }
}
